/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 *
 * @version 1.0
 */
package shop.controller.front.activitycharge;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.JSONResult;
import shop.core.plugins.wxmsg.WxMsgUtil;
import shop.services.front.activity.ActivityService;
import shop.services.front.activity.bean.Activity;
import shop.services.front.activitycharge.ActivitychargeService;
import shop.services.front.activitycharge.bean.Activitycharge;
import shop.services.front.activitypicture.ActivitypictureService;
import shop.services.front.activitypicture.bean.Activitypicture;
import shop.services.front.kcrelation.KcrelationService;
import shop.services.front.kcrelation.bean.Kcrelation;
import shop.services.front.sign.SignService;
import shop.services.front.sign.bean.Sign;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @类名称：ActivitychargeController
 * @创建人：Ltz
 * @创建时间：2017-08-29 下午21:58:55
 * @版本号：1.0
 * @描述：
 */
@Controller
@RequestMapping("/front/activitycharge")
public class ActivitychargeController extends FrontBaseController<Activitycharge> {
    @Resource
    private ActivitypictureService activitypictureService;
    @Resource
    private ActivitychargeService activitychargeService;
    @Resource
    private ActivityService activityService;
    @Resource
    private KcrelationService kcrelationService;
    @Resource
    private UserService userService;
    @Resource
    private SignService signService;

    @Override
    public Services<Activitycharge> getService() {
        return activitychargeService;
    }


    /**
     * 查询参与活动城市列表（品牌商）
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectAreaList")
    @ResponseBody
    public JSONResult selectAreaList(Activitycharge activitycharge) throws Exception {
        List<Activitycharge> rsList = activitychargeService.selectAreaList(activitycharge);
        jsonResult = new JSONResult();
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 查询参与活动合伙人列表（品牌商）
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectCityList")
    @ResponseBody
    public JSONResult selectCityList(Activitycharge activitycharge) throws Exception {
        List<Activitycharge> rsList = activitychargeService.selectCityList(activitycharge);
        jsonResult = new JSONResult();
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 查询参与活动门店列表（品牌商）
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectStoreList")
    @ResponseBody
    public JSONResult selectStoreList(Activitycharge activitycharge) throws Exception {
        List<Activitycharge> rsList = activitychargeService.selectStoreList(activitycharge);
        jsonResult = new JSONResult();
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 查询活动费用（KA经理，城市合伙人）
     *
     * @param activitycharge
     * @return
     */
    @RequestMapping(value = "/selectActivityCharge", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectActivityCharge(Activitycharge activitycharge) {
        activitycharge = getService().selectOne(activitycharge);
        jsonResult = new JSONResult();
        jsonResult.setData(activitycharge);
        return jsonResult;
    }

    /**
     * 查询参与活动门店列表（KA经理）
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectKaStoreList")
    @ResponseBody
    public JSONResult selectKaStoreList(Activitycharge activitycharge) throws Exception {
        jsonResult = new JSONResult();
        List<Activitycharge> rsList = activitychargeService.selectStoreList(activitycharge);
        for (Activitycharge rs : rsList) {
            String[] personCosts = rs.getPersonCost().split(",");
            double personCostAmount = 0.00;
            for (int i = 0; i < personCosts.length; i++) {
                personCostAmount += Double.parseDouble(personCosts[i]);
            }
            rs.setCostAmount(rs.getSiteCost() + rs.getTgCost() + personCostAmount);
        }
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 查询总费用，总补货量（KA经理）
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectAmountList")
    @ResponseBody
    public JSONResult selectAmountList(Activitycharge activitycharge) throws Exception {
        jsonResult = new JSONResult();
        DecimalFormat df = new DecimalFormat("0.00");
        List<Activitycharge> rsList = activitychargeService.selectStoreList(activitycharge);
        for (Activitycharge rs : rsList) {
            String[] personCosts = rs.getPersonCost().split(",");
            double personCostAmount = 0.00;
            for (int i = 0; i < personCosts.length; i++) {
                personCostAmount += Double.parseDouble(personCosts[i]);
            }
            rs.setCostAmount(rs.getSiteCost() + rs.getTgCost() + personCostAmount);
        }
        double chargeAmount = 0.00;
        int cargoAmount = 0;
        for (int i = 0; i < rsList.size(); i++) {
            chargeAmount += rsList.get(i).getCostAmount();
            cargoAmount += rsList.get(i).getProductAmount();
        }
        df.format(chargeAmount);
        Map<String, Object> map = new HashMap<>();
        map.put("chargeAmount", chargeAmount);
        map.put("cargoAmount", cargoAmount);
        jsonResult.setData(map);
        return jsonResult;
    }

    /**
     * 反馈费用（合伙人）
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "/insertActivitycharge", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertActivitycharge(HttpServletRequest request, Activitycharge activitycharge) throws Exception {
        jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute("userInfo");
        activitycharge.setArea(user.getAddress());
        activitycharge.setStatus("0");
        activitychargeService.insert(activitycharge);
        return jsonResult;
    }


    /**
     * 编辑反馈费用（合伙人）
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "/updateActivitycharge", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateActivitycharge(HttpServletRequest request, Activitycharge activitycharge) throws Exception {
        jsonResult = new JSONResult();
//        User user = (User) request.getSession().getAttribute("userInfo");
//        activitycharge.setArea(user.getAddress());
//        activitycharge.setStatus("0");
        activitychargeService.update(activitycharge);
        return jsonResult;
    }

    /**
     * 提交费用信息（合伙人）
     *
     * @return jsonResult
     * @throws Exception
     */
    @RequestMapping(value = "/updateCommitStatus", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateCommitStatus(Activitycharge activitycharge, @RequestParam(value = "storeIDs[]") String[] storeIDs) throws Exception {
        jsonResult = new JSONResult();
        for (int i = 0; i < storeIDs.length; i++) {//循环遍历门店
            Activitycharge rs = new Activitycharge();
            rs.setActivityID(activitycharge.getActivityID());//赋值
            rs.setCityID(activitycharge.getCityID());//赋值
            rs.setStoreID(storeIDs[i]);//赋值
            rs = activitychargeService.selectOne(rs);//查询该条门店参与记录
            if (rs != null) {//判断该条记录是否存在
                rs.setStatus("1");
                activitychargeService.update(rs);//更新状态
                Activity activity = new Activity();
                activity.setId(rs.getActivityID());
                activity = activityService.selectOne(activity);//查找该条活动
                activity.setStoreMember(activity.getStoreMember() + 1);//门店参与数量加一
                activityService.update(activity);//更新数据
            } else {
            }
        }
        Kcrelation kcrelation = new Kcrelation();
        kcrelation.setCityID(activitycharge.getCityID());
        List<Kcrelation> rsList = kcrelationService.selectKaList(kcrelation);
        logger.debug("rsList.size()" + rsList.size());
        if (rsList.size() != 0) {
            for (Kcrelation kcrelationInfo : rsList) {
                User rs = new User();
                rs.setId(kcrelationInfo.getKaID());
                rs = userService.selectOne(rs);
                Activity activity = new Activity();
                activity.setId(activitycharge.getActivityID());
                activity = activityService.selectOne(activity);
                //发送微信模版消息
                Map<String, String> msgParam = new HashMap<>();
                if (!StringUtils.isBlank(rs.getNickname()))
                    msgParam.put("first", "尊敬的" + rs.getNickname() + "，您有一条新的活动信息请及时查收！");
                msgParam.put("keyword1", activity.getKaName());
                msgParam.put("keyword2", activity.getKaStarTime() + " 至 " + activity.getKaEndTime());
                msgParam.put("keyword3", "——");
                msgParam.put("keyword4", activity.getKaDemand());
                msgParam.put("remark", "请登录平台查看活动信息");
                if (!StringUtils.isBlank(rs.getOpenID()))
                    WxMsgUtil.sendActivityStatusMsg(msgParam, systemManager.getAccessToken(), rs.getOpenID());
            }
        }
        return jsonResult;
    }

    /**
     * 查询门店列表（城市合伙人）
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectCsList")
    @ResponseBody
    public JSONResult selectCsList(Activitycharge activitycharge) throws Exception {
        List<Activitycharge> rsList = activitychargeService.selectList(activitycharge);
        if (rsList.size() != 0) {
            for (Activitycharge activitychargeInfo : rsList) {
                Activitypicture activitypicture = new Activitypicture();
                activitypicture.setActivityID(activitychargeInfo.getActivityID());
                activitypicture.setCityID(activitychargeInfo.getCityID());
                activitypicture.setStoreID(activitychargeInfo.getStoreID());
                List<Activitypicture> rsList2 = activitypictureService.selectList(activitypicture);
                if (rsList2.size() != 0) {
                    activitychargeInfo.setPictureNumber(String.valueOf(rsList2.size()));
                } else {
                    activitychargeInfo.setPictureNumber("0");
                }
            }
        }
        jsonResult = new JSONResult();
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 查询门店列表（城市合伙人打卡页面）
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectCsdList")
    @ResponseBody
    public JSONResult selectCsdList(Activitycharge activitycharge) throws Exception {
        List<Activitycharge> rsList = activitychargeService.selectList(activitycharge);
        if (rsList.size() != 0) {
            for (Activitycharge activitychargeInfo : rsList) {
                Sign sign = new Sign();
                sign.setActivityID(activitychargeInfo.getActivityID());
                sign.setCityID(activitychargeInfo.getCityID());
                sign.setStoreID(activitychargeInfo.getStoreID());
                List<Sign> rsList2 = signService.selectSignList(sign);
                if (rsList2.size() != 0) {
                    activitychargeInfo.setSignAmount(String.valueOf(rsList2.size()));
                } else {
                    activitychargeInfo.setSignAmount("0");
                }
            }
        }
        jsonResult = new JSONResult();
        jsonResult.setData(rsList);
        return jsonResult;
    }
}
